/**
 * Created by chengming on 18/5/24.
 * version 1.0
 * 人民网
 */
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const request = require('request-promise');
const vm = require('vm');
const cheerio = require('cheerio');
const urlTool = require('url');
const iconv = require("iconv-lite");
const logger = require('../../conf/logger');

module.exports = class PeoplePaper extends ArticleHrefAdapter{

	initWinEnv(){
		global.window = {
			innerWidth:1232,
			innerHeight:632,
			screenX:11,
			screenY:22,
			screen:{
				width:1280,
				height:800
			}
		};

		global.document = {
			documentElement:{
				clientWidth:1217,
				clientHeight:550
			},
			body:{
				clientWidth:1217,
				clientHeight:1467
			},
			_cookie: [],

			get cookie(){
				return this._cookie;
			},

			set cookie(val){
				this._cookie.push(val);
			}
		};
	}

	async doRequest(){

		//初始化窗口属性
		this.initWinEnv();

		//创建全局cookie
		var jar = request.jar();
		
		//使用cookie
		const body = await super.doRequest();
		return body;
	}

    parseHtml(html, linkRule){
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);

        let contents = [];
        let that = this;
        let rangeText = '';
        $(this.linkRule).each( function() {
        	let children = $(this).children()[0];
			let scriptStr = cheerio.load(children).html();
            scriptStr = scriptStr.replace("<script>document.write(view(\"","");
            scriptStr = scriptStr.replace("\"))</script>","");
            let title =scriptStr;
            let href = '';
            if($(this).is('a') && $(this).attr('href')){
                href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
            }

            if(title.length != 0 || href.length != 0){
                contents.push({
                    title:title,
                    href:href
                });
                rangeText +=title+href;
            }
        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }
}